## This script is used to save data from the web to the database
## It is a standalone script that is run once to populate the database with initial data
## It is not part of the FastAPI application

import requests
import json
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from models import User, SubCompany, Contribution, Project,Base,Plan
from config import Settings

def save_details(session,user_id,company_id):
    # Save project data
    project_response = requests.get(f"http://59.111.61.134:3625/Admin/User/details?id={user_id}&CompanyID={company_id}")
    project_datas = project_response.json()["payload"]
    # print(project_datas)
    for project_data in project_datas:
        print(project_data)
        project = session.query(Project).filter_by(id=project_data["ObjectID"]).first()
        
        if not project:
            new_project = Project(
                id=project_data["ObjectID"],
                company_id=int(project_data["CompanyID"]),
                total_number=project_data["ToNumber"],
                project_name=project_data["ProjectName"]
            )
            session.add(new_project)
        else:
            project.total_number = project_data["ToNumber"]+project.total_number
            session.add(project)
        
        for plan in json.loads(project_data["TolType"]):
            new_plan = Plan(
                project_id = project_data["ObjectID"],
                plan_name = plan["Type"],
                plan_content = '',
                admin_id = user_id,
                participants = None,
                votes = plan['Number'],
                stage = -1,
                status = 'finished'
            )
            session.add(new_plan)
        
        new_contribution = Contribution(
            user_id=int(project_data["User_ID"]),
            project_id=int(project_data["ObjectID"]),
            company_id=int(project_data["CompanyID"]),
            value=project_data["ToNumber"]
        )
        print(new_contribution)
        session.add(new_contribution)

def save_data_from_web(pagenumber=1):
    # Base.metadata.create_all(engine)
    
    # Save user data
    user_response = requests.get(f"http://59.111.61.134:3625/Admin/User/find?Current={pagenumber}&CompanyID=1")
    
    user_data = user_response.json()["payload"]["data"]
    # print(user_data)
    for user in user_data:
        ## check if the user already exists
        existing_user = session.query(User).filter_by(username=user["Name"]).first()
        if existing_user:
            continue
        new_user = User(
            id=user["UserID"],
            username=user["Name"],
            total_contribution=user["ToNumber"]
        )
        session.add(new_user)

        save_details(session,user["UserID"],1)
    
    session.commit()

if __name__ == "__main__":
    settings = Settings()
    engine = create_engine(settings.database_url)
    session = Session(engine)
    Base.metadata.create_all(engine)
    ## check if the company already exists
    company = session.query(SubCompany).filter_by(id=1).first()
    if not company:
        new_company = SubCompany(
                id=int(1),
                name= "三驱科技（杭州）有限公司",
                market_cap=1000000  # Assuming a fixed market cap for now
            )
        session.add(new_company)
    for i in range(1,80):
        save_data_from_web(pagenumber=i)